﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel;
//using System.ComponentModel.Composition;
using FRL.DebtChased.Silverlight.Library.RichContentService;
using FRL.DebtChased.Silverlight.Library;

namespace FRL.DebtChased.Silverlight.Library
{
    public partial class ContactAddressCtrl : UserControl, INotifyPropertyChanged
    {
        /////////////////////////////////////////////////////////////
        // Interface & Constructor

        public event PropertyChangedEventHandler PropertyChanged;
        public void RaisePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        public ContactAddressCtrl()
        {
            InitializeComponent();
            this.LayoutRoot.DataContext = this;
        }


        /////////////////////////////////////////////////////////////
        // Control "Parameter"

        private ContactTransport _activeContact;
        public ContactTransport ActiveContact
        {
            get { return _activeContact; }
            set
            {
                if (ActiveAddressEdited)
                    SaveActiveAddressChanges();

                this._activeContact = value;
                RaisePropertyChanged("ActiveContact");
                RaisePropertyChanged("AddressTabs");

                if (_activeContact == null)
                    this.ActiveAddress = null;
                else if (_activeContact.AddressList != null && _activeContact.AddressList.Count > 0)
                    this.ActiveAddress = value.AddressList[0];
                else
                    this.ActiveAddress = NewAddress;
            }
        }

        /////////////////////////////////////////////////////////////
        // Properties

        private ContactAddressTransport _newAddress;
        private ContactAddressTransport NewAddress
        {
            get {
                if (_newAddress == null)
                {
                    _newAddress = new ContactAddressTransport();
                    NewAddress.County = "UK";
                    NewAddress.AddressType = (int)eContactAddressType.Default;
                }
                return _newAddress; }
            set { _newAddress = value; }
        }

        private ContactAddressTransport _activeAddress;
        public ContactAddressTransport ActiveAddress
        {
            get { return _activeAddress; }
            set
            {
                if ((object.ReferenceEquals(this._activeAddress, value) != true))
                {
                    if (ActiveAddressEdited) SaveActiveAddressChanges();

                    _activeAddress = value;
                    ActiveAddressEdited = false;

                    RaisePropertyChanged("ActiveAddress");
                    RaisePropertyChanged("ActiveAddressSummary");
                    RaisePropertyChanged("ActiveAddressSummaryLabel");

                    InEditMode = (_activeAddress == NewAddress) ? true : EditMode;
                }
            }
        }
        public string ActiveAddressSummary
        {
            get
            {
                StringBuilder s = new StringBuilder();
                if (ActiveAddress != null)
                {
                    if (!string.IsNullOrWhiteSpace(ActiveAddress.AddressLineA)) s.AppendLine(ActiveAddress.AddressLineA);
                    if (!string.IsNullOrWhiteSpace(ActiveAddress.AddressLineB)) s.AppendLine(ActiveAddress.AddressLineB);
                    if (!string.IsNullOrWhiteSpace(ActiveAddress.AddressLineC)) s.AppendLine(ActiveAddress.AddressLineC);
                    if (!string.IsNullOrWhiteSpace(ActiveAddress.Postcode)) s.AppendLine(ActiveAddress.Postcode);
                }
                return s.ToString();
            }
        }
        public string ActiveAddressSummaryLabel
        {
            //get { return ((ActiveAddress != null && !string.IsNullOrWhiteSpace(ActiveAddress.Tag) ? ActiveAddress.Tag + "\n" : "") + "Address:"); }
            get { return ((ActiveAddress != null && !string.IsNullOrWhiteSpace(ActiveAddress.Postcode) ? ActiveAddress.Postcode + "\n" : "") + "Address:"); }
        }
        public IEnumerable<TabItem> AddressTabs
        {
            get
            {
                List<TabItem> tabs = new List<TabItem>();
                if (ActiveContact != null)
                {
                    if (ActiveContact.AddressList != null)
                        foreach (ContactAddressTransport address in ActiveContact.AddressList)
                        {

                            TabItem tab = new TabItem() { Header = string.Format("[{0}] {1}", RefData.GetAddressTypeCode(address.AddressType), address.Postcode), Tag = address };
                            tabs.Add(tab);
                        }
                    tabs.Add(new TabItem() { Header = "*New*", Tag = NewAddress });
                }
                return tabs;
            }
        }

        private bool _activeAddressEdited;
        public bool ActiveAddressEdited
        {
            get { return _activeAddressEdited; }
            set
            {
                if (value != _activeAddressEdited)
                {
                    _activeAddressEdited = value;
                    RaisePropertyChanged("ActiveAddressEdited");
                }
            }
        }

        private bool _EditMode;
        public bool EditMode
        {
            get { return _EditMode; }
            set
            {
                _EditMode = value;
                InEditMode = ActiveAddress != null ? _EditMode : false;
            }
        }
        private bool _inEditMode;
        private bool InEditMode
        {
            get { return _inEditMode; }
            set
            {
                if (value != _inEditMode)
                {
                    _inEditMode = value;
                    if (value)
                    {
                        AddressSummaryLabel.Visibility = Visibility.Collapsed;
                        AddressSummary.Visibility = Visibility.Collapsed;

                        AddressTypeLabel.Visibility = Visibility.Visible;
                        AddressTypeCombo.Visibility = Visibility.Visible;
                        AddressEditGrid.Visibility = Visibility.Visible;
                        //AddressTypeLabel.Opacity = 0.5;
                        //AddressTypeCombo.Opacity = 0.5;
                        //AddressEditGrid.Height = 200;
                    }
                    else
                    {
                        AddressSummaryLabel.Visibility = Visibility.Visible;
                        AddressSummary.Visibility = Visibility.Visible;

                        AddressTypeLabel.Visibility = Visibility.Collapsed;
                        AddressTypeCombo.Visibility = Visibility.Collapsed;
                        AddressEditGrid.Visibility = Visibility.Collapsed;
                        //AddressTypeLabel.Opacity = 0;
                        //AddressTypeCombo.Opacity = 0;
                        //AddressEditGrid.Height = 0;

                        RaisePropertyChanged("ActiveAddressSummary");
                        RaisePropertyChanged("ActiveAddressSummaryLabel");
                    }
                    AddressEditModeToggleButton.IsUpsideDown = !_inEditMode;
                    RaisePropertyChanged("InEditMode");
                }
            }
        }

        /////////////////////////////////////////////////////////////
        // Methods

        private bool SavingAddressChanges { get; set; }
        private void SaveActiveAddressChanges()
        {
            SavingAddressChanges = true;
            if (ActiveContact != null)
            {
                if (_activeAddress == NewAddress)
                {
                    if (ActiveContact.AddressList == null)
                        ActiveContact.AddressList = new ObservableCollection<ContactAddressTransport>();
                    ActiveContact.AddressList.Add(_activeAddress);
                    //MessageBox.Show(string.Format("Save new address for \n{0}", ActiveAddressSummary));
                    NewAddress = null;
                }
                else
                {
                    MessageBox.Show(string.Format("Save address changes for \n{0}", ActiveAddressSummary));
                }
            }
            ActiveAddressEdited = false;

            RaisePropertyChanged("AddressTabs");
            SavingAddressChanges = false;
        }

        /////////////////////////////////////////////////////////////
        // Event Handlers

        private void AddressEditModeToggleButton_Click(object sender, EventArgs e)
        {
            EditMode = !EditMode;
        }

        private void InternalTraceButton_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Internal Trace Button Clicked");
        }

        private void AddressTabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            TabControl ctrl = (TabControl)sender;
            if (ctrl.SelectedIndex >= 0)
            {
                TabItem tab = (TabItem)ctrl.Items[ctrl.SelectedIndex];
                ActiveAddress = (ContactAddressTransport)tab.Tag;
            }
            //else if (ActiveAddress != null && ctrl.Items != null)
            //{
            //    foreach (TabItem tab in ctrl.Items)
            //    {
            //        if (tab.Tag == ActiveAddress)
            //        {
            //            ctrl.SelectedItem = tab;
            //            break;
            //        }
            //    }
            //}
        }
        private void AddressTypeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (AddressTypeCombo.SelectedItem is ContactAddressType && ((ContactAddressType)AddressTypeCombo.SelectedItem).IsForeign)
            {
                AddressEditGrid.RowDefinitions[5].Height = new GridLength(0);
                AddressEditGrid.RowDefinitions[6].Height = new GridLength(0, GridUnitType.Auto);
                this.PostcodeLabel.Text = "Code:";
                this.InternalTraceButton.Visibility = Visibility.Collapsed;
            }
            else
            {
                AddressEditGrid.RowDefinitions[6].Height = new GridLength(0);
                AddressEditGrid.RowDefinitions[5].Height = new GridLength(0, GridUnitType.Auto);
                this.PostcodeLabel.Text = "Postcode:";
                this.InternalTraceButton.Visibility = Visibility.Visible;
            }
        }

        private void AddressEditGrid_KeyDown(object sender, KeyEventArgs e)
        {
            if (RefData.KeyIsEditKey(e.Key))
            {
                if (_activeAddress == NewAddress)
                {
                    int selectedIndex = AddressTabControl.SelectedIndex;
                    SaveActiveAddressChanges();
                    InEditMode = true;
                    AddressTabControl.SelectedIndex = selectedIndex;
                }
                else
                {
                    ActiveAddressEdited = true;
                }
            }
        }

        /////////////////////////////////////////////////////////////
        // Temporary Junk

        private void ResetComboBindings()
        {

        }

    }


}


